# Maintainer: Nazar Mishturak <nazar m x at gmail dot com>

_realname=mbedtls
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.28.0
pkgrel=1
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url='https://tls.mbed.org/'
pkgdesc="Portable cryptographic and SSL/TLS library, aka polarssl (mingw-w64)."
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cc")
license=('Apache')
options=('strip' '!debug' 'staticlibs')
source=("${_realname}-${pkgver}.tar.gz"::"https://github.com/ARMmbed/mbedtls/archive/v${pkgver}.tar.gz"
        'symlink-test.patch'
        'dll-location.patch'
        'enable-features.patch'
        'add-winpthread-library.patch')
sha256sums=('6519579b836ed78cc549375c7c18b111df5717e86ca0eeff4cb64b2674f424cc'
            '5c5e684de4e6295b838bd4aa3cb560221ca3b86fceab5632db15d97f6aa1e66f'
            'c6ed7ebe8bf21148e3f96eef62d1be1f5aacf3bff926dcf0837f2ff1d8fb5b2a'
            'ca8e32685891e3c167a0cb67ee4525b1889a3f59a0b5b0161deaf2869656a00b'
            '17bcdbcabc75cbf850de8ae4479b2017526684f183de063b817555270fc00fd0')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/symlink-test.patch"
  patch -p1 -i "${srcdir}/dll-location.patch"
  patch -p1 -i "${srcdir}/enable-features.patch"
  patch -p1 -i "${srcdir}/add-winpthread-library.patch"
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  [[ -d "${srcdir}/build-${MINGW_CHOST}" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}"
  mkdir -p "${srcdir}/build-${MINGW_CHOST}" && cd "${srcdir}/build-${MINGW_CHOST}"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    "${_extra_config[@]}" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DENABLE_PROGRAMS=ON \
    -DENABLE_TESTING=ON \
    -DMBEDTLS_FATAL_WARNINGS=OFF \
    -DUSE_SHARED_MBEDTLS_LIBRARY=ON \
    -DUSE_STATIC_MBEDTLS_LIBRARY=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MINGW_CHOST}"

  # Tests are dynamically linked
  PATH=$PWD/library:$PATH ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target test || true
}

package () {
  cd "${srcdir}/build-${MINGW_CHOST}"
  DESTDIR=${pkgdir} ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

  # rename generic utils
  local _prog _baseprog
  for _prog in "$pkgdir${MINGW_PREFIX}"/bin/*.exe; do
    _baseprog=$(basename "$_prog")
    mv "$_prog" "${_prog//$_baseprog/mbedtls_$_baseprog}"
  done

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
